#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

MdiChild* MainWindow::createMdiChild()
{
    MdiChild *child = new MdiChild;
    ui->mdiArea->addSubWindow(child);

    return child;
}

bool MainWindow::loadFile(const QString& fileName)
{
    QFile file(fileName);

    // loop loading until user says stop
    while(true)
    {
        if( file.open(QFile::ReadOnly | QFile::Text) == true)
            break;

        // an error occured
        const QMessageBox::StandardButton reply =
                QMessageBox::warning(this, tr("Failed to open file"),
                                     tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()),
                                     QMessageBox::Abort | QMessageBox::Retry | QMessageBox::Ignore);
        if (reply == QMessageBox::Abort)
            return false;
        else if (reply == QMessageBox::Retry)
        {
            //continue;
        }
        else // ignore
        {
            return true;
        }
    }

    MdiChild* child = createMdiChild();
    QTextStream in(&file);
    child->loadFile(fileName, in);
    child->show();
    return true;
}

MdiChild *MainWindow::activeMdiChild()
{
    if (QMdiSubWindow *activeSubWindow = ui->mdiArea->activeSubWindow())
        return qobject_cast<MdiChild *>(activeSubWindow->widget());
    return 0;
}

QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName)
{
    QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();

    foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList()) {
        MdiChild *mdiChild = qobject_cast<MdiChild *>(window->widget());
        if (mdiChild->currentFile() == canonicalFilePath)
            return window;
    }
    return 0;
}

void MainWindow::setActiveSubWindow(QWidget *window)
{
    if (!window)
        return;
    ui->mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow *>(window));
}


///////////////////////////////////// triggers

void MainWindow::on_actionNew_Python_module_triggered()
{
    MdiChild* n = createMdiChild();
    n->newFile();
    n->show();
}

void MainWindow::on_actionOpen_triggered()
{
    QStringList files = QFileDialog::getOpenFileNames(
                this, tr("Open python modules"),
                QString(), tr("All Files (*);;Text Files (*.txt)"));
    for(int i=0; i<files.count(); ++i)
    {
        QString file = files[i];

        QMdiSubWindow *existing = findMdiChild(file);
        if (existing)
        {
            ui->mdiArea->setActiveSubWindow(existing);
            return;
        }

        if( false == loadFile(file) ) return;
    }
}

void MainWindow::on_actionSave_triggered()
{
    if (activeMdiChild() && activeMdiChild()->save())
        statusBar()->showMessage(tr("File saved"), 2000);
}

void MainWindow::on_actionSave_as_triggered()
{
    if (activeMdiChild() && activeMdiChild()->saveAs())
        statusBar()->showMessage(tr("File saved"), 2000);
}

void MainWindow::on_actionClose_triggered()
{
    QMdiSubWindow* w= ui->mdiArea->activeSubWindow();
    if( w )
    {
        w->close();
        statusBar()->showMessage(tr("Window closed"), 2000);
    }
}

void MainWindow::on_actionClose_all_triggered()
{
    ui->mdiArea->closeAllSubWindows();
}

void MainWindow::on_actionSave_all_triggered()
{
    foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList())
    {
        MdiChild* mdiChild = qobject_cast<MdiChild *>(window->widget());
        mdiChild->save();
    }
}

void MainWindow::on_actionExit_triggered()
{
    close();
}

void MainWindow::on_actionCut_triggered()
{
    if (activeMdiChild() )
        activeMdiChild()->cut();
}

void MainWindow::on_actionCopy_triggered()
{
    if (activeMdiChild() )
        activeMdiChild()->copy();
}

void MainWindow::on_actionPaste_triggered()
{
    if (activeMdiChild() )
        activeMdiChild()->paste();
}
